package com.hfh.thread_contr;

public class DaemonDemo extends Thread{
    public static void main(String[] args) {
        // 获取当前线程
        Thread thread = Thread.currentThread();
        // 获取线程的名称
        String name = thread.getName();
        System.out.println(name);

        for (char c = 'a'; c <= 'z'; c++) {
            if (c == 'f') {
                // 创建线程
                Thread t1 = new DaemonDemo();

                // 设置线程名称
                t1.setName("线程1");

                // 设置t1 为后台线程
                t1.setDaemon(true);

                t1.start();
            }
            // 让线程睡眠一会, 当前线程在睡眠的时候, cpu会找其他的线程并执行
            try {
                Thread.sleep(30);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            System.out.println(name + ":" + c);
        }

    }

    @Override
    public void run() {
        for (int i = 1; i <= 100; i++) {
            // 在 Thread子类里面获取线程名, 直接调用getName
            String name = getName();
            try {
                Thread.sleep(30);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(name + ":" + i);
        }
    }
    /*public static void main(String[] args) {
        Thread thread = new DaemonDemo();
        thread.setName("线程1");
        thread.setDaemon(true);//设置后台线程
        thread.start();
        for (char c = 'a';c<='z';c++){
            System.out.println(Thread.currentThread().getName()+":"+c);
        }
    }

    @Override
    public void run() {
        for (int i = 1;i<=100;i++){
            System.out.println(getName()+":"+i);
        }
    }*/
}
